package com.pirestupppai.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.gson.JsonObject;
import com.pirestupppai.R;
import com.pirestupppai.base.BaseActivity;
import com.pirestupppai.common.Constant;
import com.pirestupppai.common.Urls;
import com.pirestupppai.network.NetworkRequest;
import com.pirestupppai.network.TupaiSubscriber;
import com.pirestupppai.utils.OauthUtil;
import com.pirestupppai.utils.StringUtil;
import com.pirestupppai.utils.Utils;
import com.pirestupppai.utils.WeakReferenceHandler;
import com.pirestupppai.widgets.dialog.ProgressingDialog;

import java.util.HashMap;

import butterknife.BindView;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;


/**
 * 输入手机号页
 *
 * @author: xiaoluo
 * @date: 2017-03-01 14:40
 */
public class InputPhoneActivity extends BaseActivity {
    private final static String TAG = InputPhoneActivity.class.getSimpleName();

    @BindView(R.id.logo_click_iv)
    ImageView logoIv;
    @BindView(R.id.phone_et)
    EditText phoneEt;
    @BindView(R.id.next_btn)
    Button nextBtn;
    @BindView(R.id.weibo_login)
    ImageView weiboBtn;
    @BindView(R.id.qq_login)
    ImageView qqBtn;
    @BindView(R.id.weixin_login)
    ImageView weixinBtn;
    @BindView(R.id.parent_layout)
    LinearLayout parentLayout;

    private static final int OAUTH_ERROR = 500;
    private static final int OAUTH_CANCEL = 600;
    private static final int OAUTH_SUCCESS = 700;

    private WeakReferenceHandler mHandler = new WeakReferenceHandler(this);
    private Platform mPlatform;
    private ProgressingDialog mDialog;
    private int mClickCount = 0;

    @Override
    protected Context getActivityContext() {
        return this;
    }

    @Override
    protected int loadParentLayout() {
        return R.layout.activity_input_phone;
    }

    @Override
    protected void initViews() {
        mDialog = new ProgressingDialog(mContext);
        if (mDialog != null) {
            mDialog.dismiss();
        }

        if (Urls.BASE_URL == Urls.RELEASE_URL) {
            parentLayout.setBackgroundColor(getResources().getColor(R.color.white));
        } else {
            parentLayout.setBackgroundColor(getResources().getColor(R.color.colorAccent));
        }
    }

    @Override
    protected void initListeners() {
        nextBtn.setOnClickListener(this);
        qqBtn.setOnClickListener(this);
        weiboBtn.setOnClickListener(this);
        weixinBtn.setOnClickListener(this);
        logoIv.setOnClickListener(this);
    }


    @Override
    protected void initLogic() {
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.next_btn:
                nextBtn.setClickable(false);
                checkPhone();
                break;
            case R.id.logo_click_iv:
                enterTestStatus();
                break;
            case R.id.qq_login:
                oauthLogin(OauthUtil.PLATFORM_QQ);
                break;
            case R.id.weibo_login:
                oauthLogin(OauthUtil.PLATFORM_WEIBO);
                break;
            case R.id.weixin_login:
                oauthLogin(OauthUtil.PLATFORM_WECHAT);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        finish();
//        System.exit(0);
    }

    /**
     * 进入测试状态
     */
    private void enterTestStatus() {
        if (mClickCount < 10) {
            mClickCount++;
        } else {
            mClickCount = 0;
            if (Urls.BASE_URL == Urls.RELEASE_URL) {
                Urls.BASE_URL = Urls.TEST_URL;
                parentLayout.setBackgroundColor(getResources().getColor(R.color.colorAccent));
                Utils.showToast("进入测试环境");
                NetworkRequest.getInstance().clearNetwork();
            } else {
                Urls.BASE_URL = Urls.RELEASE_URL;
                parentLayout.setBackgroundColor(getResources().getColor(R.color.white));
                Utils.showToast("进入正式环境");
                NetworkRequest.getInstance().clearNetwork();
            }
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        switch (msg.what) {
            case OAUTH_ERROR:
                Utils.showToast("授权出错");
                break;
            case OAUTH_CANCEL:
                Utils.showToast("取消");
                break;
            case OAUTH_SUCCESS:
                OauthUtil.oauthLogin(mContext, mPlatform, (String) msg.obj);
                break;
        }
        return super.handleMessage(msg);
    }

    /**
     * 手机号校验是否注册
     */
    private void checkPhone() {
        if (validate()) {
            NetworkRequest.getInstance().checkPhone(phoneEt.getText().toString().trim(),
                    new TupaiSubscriber<JsonObject>(mContext) {
                        @Override
                        protected void requestSuccess(JsonObject jsonObject) {
                            nextBtn.setClickable(true);
                            boolean isRegister = jsonObject.get("exist").getAsBoolean();
                            // 已注册跳到登录页,未注册跳到注册页
                            Intent intent = new Intent();
                            if (isRegister) {
                                intent.setClass(mContext, LoginActivity.class);
                            } else {
                                intent.setClass(mContext, RegisterActivity.class);
                            }
                            intent.putExtra(Constant.IntentKey.PHONE, phoneEt.getText().toString().trim());
                            startActivity(intent);
                        }

                        @Override
                        protected void requestError(String error) {
                            nextBtn.setClickable(true);
                        }
                    });
        }
    }
    
    /**
     * 手机号校验
     */
    private boolean validate() {
        if (TextUtils.isEmpty(phoneEt.getText().toString())) {
            Utils.showToast("请填写手机号码");
            phoneEt.requestFocus();
            nextBtn.setClickable(true);
            return false;
        }

        if (!StringUtil.matchPhoneNum(phoneEt.getText().toString().trim())) {
            Utils.showToast("手机号格式不正确");
            phoneEt.requestFocus();
            nextBtn.setClickable(true);
            return false;
        }

        return true;
    }

    /**
     * 第三方授权登录
     */
    private void oauthLogin(final String name) {
        mDialog.show();
        Platform platform = null;
        switch (name) {
            case OauthUtil.PLATFORM_QQ:
                platform = ShareSDK.getPlatform(QQ.NAME);
                break;
            case OauthUtil.PLATFORM_WEIBO:
                platform = ShareSDK.getPlatform(SinaWeibo.NAME);
                break;
            case OauthUtil.PLATFORM_WECHAT:
                platform = ShareSDK.getPlatform(Wechat.NAME);
                break;
        }
        platform.SSOSetting(false); //设置false表示使用SSO授权方式,优先调用客户端
        //authorize与showUser单独调用一个即可
        platform.authorize(); //单独授权,OnComplete返回的hashmap是空的
//        platform.showUser(null);//授权并获取用户信息
        if (platform.isAuthValid()) {
            platform.removeAccount(true);
        }

        final Message message = Message.obtain();
        message.obj = name;
        platform.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                mPlatform = platform;
                message.what = OAUTH_SUCCESS;
                mHandler.sendMessage(message);
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                message.what = OAUTH_ERROR;
                mHandler.sendMessage(message);
            }

            @Override
            public void onCancel(Platform platform, int i) {
                message.what = OAUTH_CANCEL;
                mHandler.sendMessage(message);
            }
        });
    }
}
